package com.ansion.commonchat.startup.workmanager.bwork.utils;

import androidx.annotation.NonNull;
import androidx.annotation.WorkerThread;

import com.ansion.commonchat.startup.workmanager.bwork.BWorkInfo;
import com.ansion.commonchat.startup.workmanager.bwork.impl.BWorkManagerImpl;
import com.ansion.commonchat.startup.workmanager.bwork.impl.mode.BWorkSpec;
import com.ansion.commonchat.startup.workmanager.bwork.utils.futures.BSettableFuture;
import com.google.common.util.concurrent.ListenableFuture;

import java.util.List;
import java.util.UUID;

/**
 * Created by wanghongjie on 2023/5/11
 * Describe : 用于执行工作状态的更新操作
 */
public abstract class BStatusRunnable<T> implements Runnable {
    private final BSettableFuture<T> mFuture = BSettableFuture.create();

    public BStatusRunnable() {
    }

    public void run() {
        try {
            T value = this.runInternal();
            this.mFuture.set(value);
        } catch (Throwable var2) {
            this.mFuture.setException(var2);
        }

    }

    @WorkerThread
    abstract T runInternal();

    @NonNull
    public ListenableFuture<T> getFuture() {
        return this.mFuture;
    }

    @NonNull
    public static BStatusRunnable<BWorkInfo> forUUID(@NonNull final BWorkManagerImpl workManager, @NonNull final UUID id) {
        return new BStatusRunnable<BWorkInfo>() {
            BWorkInfo runInternal() {
                BWorkSpec.BWorkInfoPojo workInfoPojo = workManager.getWorkDataCache().workSpecDao().getWorkStatusPojoForId(id.toString());
                return workInfoPojo != null ? workInfoPojo.toWorkInfo() : null;
            }
        };
    }

    @NonNull
    public static BStatusRunnable<List<BWorkInfo>> forTag(
            @NonNull final BWorkManagerImpl workManager,
            @NonNull final String tag) {

        return new BStatusRunnable<List<BWorkInfo>>() {
            @Override
            List<BWorkInfo> runInternal() {
                return workManager.getWorkDataCache().workSpecDao().getWorkInfosForTag(tag);
            }
        };
    }

}